package cn.zzf.leetcode;

public class T0013_RomanToInt {

    private final static String[] thousands = {"", "M", "MM", "MMM"};
    private final static String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    private final static String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    private final static String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

    public static int romanToInt(String s) {
        int result = 0;
        if (s.startsWith("M")) {
            for (int i = thousands.length - 1; i >= 0; i--) {
                if (s.startsWith(thousands[i])) {
                    s = s.substring(thousands[i].length());
                    result += i * 1000;
                }
            }
        }
        if (s.startsWith("C") || s.startsWith("D")) {
            for (int i = hundreds.length - 1; i >= 0; i--) {
                if (s.startsWith(hundreds[i])) {
                    s = s.substring(hundreds[i].length());
                    result += i * 100;
                }
            }
        }
        if (s.startsWith("X") || s.startsWith("L")) {
            for (int i = tens.length - 1; i >= 0; i--) {
                if (s.startsWith(tens[i])) {
                    s = s.substring(tens[i].length());
                    result += i * 10;
                }
            }
        }
        if (s.startsWith("V") || s.startsWith("I")) {
            for (int i = ones.length - 1; i >= 0; i--) {
                if (s.startsWith(ones[i])) {
                    s = s.substring(ones[i].length());
                    result += i;
                }
            }

        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(romanToInt("III"));
        System.out.println(romanToInt("IV"));
        System.out.println(romanToInt("IX"));
        System.out.println(romanToInt("LVIII"));
        System.out.println(romanToInt("MCMXCIV"));
    }

}
